//
//  BSSeeBigPictureViewController.m
//  baisibudejie
//
//  Created by 陈博文 on 15/12/28.
//  Copyright © 2015年 陈博文. All rights reserved.
//

#import "BSSeeBigPictureViewController.h"
#import <UIImageView+WebCache.h>
#import "BSTopic.h"
#import <SVProgressHUD.h>
@interface BSSeeBigPictureViewController ()<UIScrollViewDelegate>

@property (weak, nonatomic) IBOutlet UIButton *backButton;

@property (weak, nonatomic) IBOutlet UIButton *saveImageButton;

/** imageView*/
@property (nonatomic ,weak) UIImageView *imageView;
@end



@implementation BSSeeBigPictureViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // scrollView
    UIScrollView *scrollView = [[UIScrollView alloc] init];
    //    scrollView.frame = [UIScreen mainScreen].bounds;
    scrollView.frame = self.view.bounds;
    scrollView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    [scrollView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(back:)]];
    [self.view insertSubview:scrollView atIndex:0];
    
    // imageView
    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.width = BSScreenW;
    imageView.height = self.topic.height * imageView.width / self.topic.width;
    imageView.x = 0;
    if (imageView.height > BSScreenH) { // 图片高度 > 屏幕高度
        imageView.y = 0;
        scrollView.contentSize = CGSizeMake(0, imageView.height);
    } else {
        imageView.centerY = BSScreenH * 0.5;
    }
    // 下载大图片
    [imageView sd_setImageWithURL:[NSURL URLWithString:self.topic.image1] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        self.saveImageButton.enabled = YES;
    }];
    [scrollView addSubview:imageView];
    self.imageView = imageView;
    
    // 设置最大缩放比例
    CGFloat scale = self.topic.width / imageView.width;
    if (scale > 1.0) {
        scrollView.maximumZoomScale = scale;
        scrollView.delegate = self;
    }
}


- (IBAction)back:(id)sender {
    
    [self dismissViewControllerAnimated:YES completion:nil];
}


- (IBAction)saveButton:(id)sender {
    
    UIImageWriteToSavedPhotosAlbum(self.imageView.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);

}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (error) {
        [SVProgressHUD showErrorWithStatus:@"保存失败!"];
    } else {
        [SVProgressHUD showSuccessWithStatus:@"保存成功!"];
    }
}

#pragma mark - <UIScrollViewDelegate>
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return self.imageView;
}


@end
